package com.jewaton.auth.sensitive;


import com.jewaton.auth.commons.SystemContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.net.URLDecoder;
import java.util.Map;

public class SensitiveHttpServletRequestWrapper extends
		HttpServletRequestWrapper {
	private static final Logger logger=LoggerFactory.getLogger(SensitiveServiceBean.class);
	private SensitiveService sensitiveService;
	private static final String ENCODING = "UTF-8";

	public SensitiveHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		try {
			WebApplicationContext springContext=(WebApplicationContext) SystemContext.getContext().get(SystemContext.SPRING_APPLICATION_CONTEXT);
			//WebApplicationContext springContext=WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
			sensitiveService=(SensitiveService)springContext.getBean("sensitiveService");
			String method = request.getMethod();
			if("get".equalsIgnoreCase((method)) || "post".equalsIgnoreCase((method))){
                Map<String, String[]> map=request.getParameterMap();
                for(String name : map.keySet()){
                    String[] values = map.get(name);
                    if(values == null || values.length <= 0) continue;
                    for (int i = 0; i < values.length; i++) {
                        if(StringUtils.isNotBlank(values[i])){
                            String value = URLDecoder.decode(values[i], ENCODING).trim();
                            if(logger.isDebugEnabled()){
                                logger.debug("replace before: " + name +" = " + value);
                            }
                            values[i]= sensitiveService.replace(value);
                            if(logger.isDebugEnabled()){
                                logger.debug("replaced after: " + name +" = " + values[i]);
                            }
                        }
                    }
                }
				/*Enumeration<String> names = request.getParameterNames();
				while(names.hasMoreElements()){
					String name = names.nextElement();
					String[] values = request.getParameterValues(name);
					try {
						String[] replacedValue = new String[values.length];
						if(values == null || values.length <= 0) continue;
						for (int i = 0; i < values.length; i++) {
							if(StringUtils.isNotBlank(values[i])){
								String value = URLDecoder.decode(values[i], ENCODING).trim();
								if(logger.isDebugEnabled()){
									logger.debug("replace before: " + name +" = " +value);
								}
								replacedValue[i]= sensitiveService.replace(value);
								if(logger.isDebugEnabled()){
									logger.debug("replaced after: " + name +" = " +replacedValue[i]);
								}
							}
						}
						request.setAttribute(name, replacedValue);
					} catch (Exception e) {
						logger.error(e.getMessage(),e);
					}
				}*/
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}

	@Override
	public String getParameter(String name) {
		// TODO Auto-generated method stub
		String value = super.getParameter(name);
		try {
			if(StringUtils.isNotBlank(value)){
				value= sensitiveService.replace(value);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return value;
	}

	@Override
	public String[] getParameterValues(String name) {
		// TODO Auto-generated method stub
		String[] values= super.getParameterValues(name);
		try {
			if(values != null){
				for(int i=0;i<values.length;i++) {
					values[i]=sensitiveService.replace(values[i]);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return values;
	}

}
